#include "../include/threadPool.h"
int sendCommand(int sockfd, Command cmd, const char *data, int data_length)
{
    protocol_header_t header;
    header.magic = MAGIC_NUMBER;
    header.data_length = data_length;
    header.command = cmd;

    int ret = send(sockfd, &header, HEADER_LENGTH, 0);
    ERROR_CHECK(ret, 0, "client send header failed");

    if (data_length > HEADER_LENGTH && data != NULL)
    {
        ret = send(sockfd, data, data_length, 0);
        ERROR_CHECK(ret, 0, "client send data_body failed");
    }
    return 0;
}
int recvCommand(int sockfd, Command *cmd, char *buf, int *buf_length)
{
    // 接收数据头
    protocol_header_t header;
    int header_length = HEADER_LENGTH;
    int ret = recv(sockfd, &header, HEADER_LENGTH, MSG_WAITALL);
    ERROR_CHECK(ret, HEADER_LENGTH, "client recv header failed");
    // 验证magic number
    ERROR_CHECK(header.magic, MAGIC_NUMBER, "recv header magic failed");
    // 接收数据体
    if (header.data_length > 0)
    {
        if (header.data_length > *buf_length)
        {
            printf("data too large……\n");
            return -1;
        }
        recv(sockfd, buf, sizeof(buf), MSG_WAITALL);
    }
    *cmd = (Command)header.command;
    *buf_length = header.data_length;
    return 0;
}
